import { getUserPageList, addUser, updateUser, updateUserStatus } from '@/api/user'
import { removeUsersFromOrg } from '@/api/org'

export default {
  data() {
    return {
      loading: false,
      userList: [],
      total: 0,
      searchForm: {
        page: 1,
        pageSize: 10,
        status: ''
      },
      // 用户表单
      userDialogVisible: false,
      userDialogTitle: '添加用户',
      userForm: {
        uid: null,
        userId: '',
        email: '',
        password: '',
        status: '1',
        orgId: ''
      },
      userRules: {
        userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      // 多选
      selectedUsers: []
    }
  },
  mounted() {
    // 从路由参数预填机构筛选
    const routeOrgId = this.$route && this.$route.query && this.$route.query.org_id
    if (routeOrgId) {
      this.searchForm.org_id = routeOrgId
    }
    this.getUserList()
  },
  methods: {
    // 获取状态按钮类型
    getStatusButtonType(status) {
      switch (status) {
        case '1': return 'warning' // 启用 -> 封禁
        case '2': return 'success' // 封禁 -> 启用
        case '3': return 'info' // 已排除 -> 不可操作
        default: return 'warning'
      }
    },

    // 获取状态按钮文本
    getStatusButtonText(status) {
      switch (status) {
        case '1': return '封禁'
        case '2': return '启用'
        case '3': return '已排除'
        default: return '未知'
      }
    },

    // 获取用户列表
    async getUserList() {
      this.loading = true
      try {
        const result = await getUserPageList(this.searchForm)
        if (result && result.code === 1) {
          const data = result.data || {}
          this.userList = data.records || []
          this.total = data.total || 0
        } else {
          this.$message.error(`获取用户列表失败: ${result?.msg || '未知错误'}`)
        }
      } catch (error) {
        this.$message.error(`获取用户列表异常: ${error.message}`)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.searchForm.page = 1
      this.getUserList()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        page: 1,
        pageSize: 10,
        status: '',
        org_id: ''
      }
      this.getUserList()
    },

    // 分页
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getUserList()
    },

    handleCurrentChange(val) {
      this.searchForm.page = val
      this.getUserList()
    },

    // 表格多选变更
    handleSelectionChange(selection) {
      this.selectedUsers = Array.isArray(selection) ? selection : []
    },

    // 批量将账户移出机构
    async batchRemoveFromOrg() {
      if (!this.selectedUsers.length) {
        this.$message.warning('请先选择需要移出的用户')
        return
      }
      const uidList = this.selectedUsers.map(u => u.uid).filter(Boolean)
      if (!uidList.length) {
        this.$message.warning('所选用户缺少UID，无法操作')
        return
      }
      try {
        await this.$confirm(`确定将选中的 ${uidList.length} 个账号移出机构吗？`, '批量移出机构', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
      } catch (e) {
        return
      }
      try {
        const res = await removeUsersFromOrg(uidList)
        if (res && res.code === 1) {
          this.$message.success('已移出机构')
          // 清空选择
          if (this.$refs && this.$refs.userTable && this.$refs.userTable.clearSelection) {
            this.$refs.userTable.clearSelection()
          }
          this.selectedUsers = []
          // 刷新列表
          this.getUserList()
        } else {
          this.$message.error(`移出失败: ${res?.msg || '未知错误'}`)
        }
      } catch (error) {
        this.$message.error(`移出异常: ${error.message}`)
      }
    },

    // 显示添加用户对话框
    showAddUserDialog() {
      this.userDialogTitle = '添加用户'
      this.userForm = {
        uid: null,
        userId: '',
        email: '',
        password: '',
        status: '1',
        orgId: ''
      }
      this.userDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.userForm && this.$refs.userForm.clearValidate) {
          this.$refs.userForm.clearValidate()
        }
      })
    },

    // 编辑用户
    editUser(row) {
      this.userDialogTitle = '编辑用户'
      this.userForm = {
        uid: row.uid,
        userId: row.userId,
        email: row.email,
        password: '',
        status: row.status,
        orgId: row.orgId || ''
      }
      this.userDialogVisible = true
    },

    // 保存用户
    saveUser() {
      if (!this.$refs.userForm || !this.$refs.userForm.validate) return
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          try {
            if (this.userForm.uid) {
              // 编辑用户
              const updateData = {
                uid: this.userForm.uid,
                userId: this.userForm.userId,
                email: this.userForm.email,
                status: this.userForm.status,
                orgId: this.userForm.orgId
              }
              // 如果修改了密码，则包含密码字段
              if (this.userForm.password) {
                updateData.password = this.userForm.password
              }
              await updateUser(updateData)
              this.$message.success('用户更新成功')
            } else {
              // 添加用户
              const addData = {
                userId: this.userForm.userId,
                email: this.userForm.email,
                password: this.userForm.password,
                status: this.userForm.status,
                orgId: this.userForm.orgId
              }
              await addUser(addData)
              this.$message.success('用户添加成功')
            }
            this.userDialogVisible = false
            this.getUserList()
          } catch (error) {
            this.$message.error(`保存失败: ${error.message}`)
          }
        }
      })
    },

    // 切换状态
    async toggleStatus(row) {
      try {
        let newStatus
        if (row.status === '1') {
          newStatus = '2' // 启用 -> 封禁
        } else if (row.status === '2') {
          newStatus = '1' // 封禁 -> 启用
        } else {
          this.$message.warning('已排除状态的用户无法修改状态')
          return
        }
        await updateUserStatus({ user_uid: row.uid, status: newStatus })
        this.$message.success('状态更新成功')
        this.getUserList()
      } catch (error) {
        this.$message.error(`更新状态失败: ${error.message}`)
      }
    },

    // 删除用户（通过状态置为3）
    deleteUser(row) {
      this.$confirm('确定删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await updateUserStatus({ user_uid: row.uid, status: '3' })
          this.$message.success('删除成功')
          this.getUserList()
        } catch (error) {
          this.$message.error(`删除失败: ${error.message}`)
        }
      }).catch(() => {})
    },

    // 详情
    viewDetails(row) {
      if (!row || !row.uid) {
        this.$message.error('无法打开详情：缺少用户UID')
        return
      }
      this.$router.push({
        path: '/user/detail',
        query: { user_uid: row.uid }
      })
    },

    // 截断文本显示
    truncateText(text, maxLength = 20) {
      if (!text) return ''
      if (text.length <= maxLength) return text
      return text.substring(0, maxLength) + '...'
    },

    // 复制到剪贴板
    async copyToClipboard(text) {
      try {
        if (navigator.clipboard && window.isSecureContext) {
          // 使用现代 Clipboard API
          await navigator.clipboard.writeText(text)
          this.$message.success('复制成功')
        } else {
          // 降级方案：使用传统方法
          const textArea = document.createElement('textarea')
          textArea.value = text
          textArea.style.position = 'fixed'
          textArea.style.left = '-999999px'
          textArea.style.top = '-999999px'
          document.body.appendChild(textArea)
          textArea.focus()
          textArea.select()
          document.execCommand('copy')
          textArea.remove()
          this.$message.success('复制成功')
        }
      } catch (error) {
        console.error('复制失败:', error)
        this.$message.error('复制失败，请手动复制')
      }
    }
  }
}
